package com.jinlejia.erp.ui.mine.sign;

import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityOutItemsBinding;
import com.jinlejia.erp.ui.mine.adapter.OutItemsAdapter;
import com.jinlejia.erp.utils.DataFilter;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;

/**
 * 外出事项
 */
public class OutItemsActivity extends AppCompatActivity {


    ArrayList<Map<String, String>> data = new ArrayList<>();
    OutItemsAdapter adapter;

    private ActivityOutItemsBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_out_items);
        binding.backBtn.setOnClickListener(view -> finish());
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerView.setHasFixedSize(true);
        binding.recyclerView.setDivider(R.drawable.shape_h_line);
        adapter = new OutItemsAdapter(data);
        adapter.changeMode(YfListMode.MODE_LOADING);
        binding.recyclerView.setAdapter(adapter);
        getData();
        adapter.setOnItemSelectedListener((name, value) -> {
            Intent data = new Intent();
            data.putExtra("name", name);
            data.putExtra("value", value);
            setResult(RESULT_OK, data);
            finish();
        });

    }

    private void getData() {
        OkHttpUtils.get()
                .url(ApiConfig.OUT_ITEMS_LIST)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        call.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(OutItemsActivity.this, response, adapter)) {
                            JSONObject object = JSON.parseObject(response.get("data").toString());
                            ArrayList<Map<String, String>> list = JSON.parseObject(object.getJSONArray("outTypeList").toJSONString(), new TypeReference<ArrayList<Map<String, String>>>() {
                            });

                            adapter.setData(list);
                        }
                    }
                });
    }
}
